package alogrithm;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;

/**
 * @author lbw
 * @version 1.0
 * @date 2021/10/16 11:32
 */
public class Solve {
    public static void main(String[] args) {
        System.out.println(new Solve().solve("(2*(3-4))*5"));
    }

    public int solve(String s) {
        s = s.trim();
        Deque<Integer> stack = new ArrayDeque<>();
        int number = 0;
        char sign = '+';
        char[] chars = s.toCharArray();
        for (int i = 0, n = chars.length; i < n; ++i) {
            char c = chars[i];
            if (c == ' ') {
                continue;
            }
            if (Character.isDigit(c)) {
                number = number * 10 + c - '0';
            }
            if (c == '(') {
                int j = i + 1;
                int countPartition = 1;
                while (countPartition > 0) {
                    if (chars[j] == '(') {
                        countPartition++;
                    }
                    if (chars[j] == ')') {
                        countPartition--;
                    }
                    j++;
                }
                number = solve(s.substring(i + 1, j - 1));
                i = j - 1;
            }
            if (!Character.isDigit(c) || i == n - 1) {
                if (sign == '+') {
                    stack.push(number);
                } else if (sign == '-') {
                    stack.push(-1 * number);
                } else if (sign == '*') {
                    stack.push(stack.pop() * number);
                } else if (sign == '/') {
                    stack.push(stack.pop() / number);
                }
                number = 0;
                sign = c;
            }
        }
        int res = 0;
        while (!stack.isEmpty()) {
            res += stack.pop();
        }
        return res;
    }

}
